#coding=utf-8
#要点：ctypes调用c接口的传入字符串应当把字符串转换为bytes

from ctypes import *
dll = CDLL("./libmsc.so")
MSP_SUCCESS = 0
MSP_TTS_FLAG_STILL_HAVE_DATA = 1
MSP_TTS_FLAG_DATA_END = 2
MSP_TTS_FLAG_CMD_CANCELED = 4


class Myttb():
    def __init__(self):
        #初始化，只需要调用一次即可
        print("讯飞离线语音合成sdk登录中》》》")
        login_params = b"appid =你的ID, work_dir = ."
        ret = dll.MSPLogin(None, None, login_params)#登录
        self.session_begin_params = b"engine_type = local,voice_name=xiaofeng, text_encoding = UTF8, tts_res_path = fo|res/tts/xiaofeng.jet;fo|res/tts/common.jet, sample_rate = 16000, speed = 50, volume = 50, pitch = 50, rdn = 2"

    def __getData(self,text):
        dataBuff=bytes()#用来暂存音频数据
        ret, audio_len, synth_status, getret,= c_int(), c_int(), c_int(), c_int()
        dll.QTTSSessionBegin.restype=c_char_p #设置原生函数返回值为char指针 
        sessionID = dll.QTTSSessionBegin(self.session_begin_params, byref(ret))
        ret = dll.QTTSTextPut(sessionID, text, len(text), None)
        while True:
            dll.QTTSAudioGet.restype=c_void_p#设置原生函数返回为void指针
            data = dll.QTTSAudioGet(sessionID, byref(audio_len), byref(synth_status), byref(getret))
            if getret.value != MSP_SUCCESS:
                print(getret)#如果不是正常结束会打印错误码
                break
            if data:
                dataBuff=dataBuff+string_at(data, audio_len)
            if synth_status.value == MSP_TTS_FLAG_DATA_END:
                break#正常结束
        dll.QTTSSessionEnd(sessionID, "Normal")
        return dataBuff

    def my_tts(self,text):
        text=text.encode("utf-8")
        return self.__getData(text)

    def __del__(self):
        dll.MSPLogout()
        print("讯飞离线语音合成sdk已登出")

ttbObj=Myttb()